<template>
  <div class="app-container">



    <!-- 添加或修改就诊信息对话框 -->
      <el-tabs type="border-card" v-model="activeName"  @tab-click="handleClick">

        <el-tab-pane name="1" label="基本信息">
          <el-form ref="patientForm" :rules="patientrules" :model="patientForm" label-width="100px" label-position="top">
            <el-row :gutter="10">
              <el-row :gutter="10">
                <el-col :span="10">
                  <el-form-item label="身份证号" prop="patientIdentityNo">
                    <el-input v-model="patientForm.patientIdentityNo" placeholder="请输入患者身份证号" readonly maxlength="18"/>
                  </el-form-item>
                </el-col>
                <el-col :span="2">
                  <span ref="checkPatient"></span>
                </el-col>
<!--                <el-col :span="8" :offset="4">-->
<!--                  <el-form-item label="患者编号(只读)" prop="patientNo">-->
<!--                    <el-input v-model="patientForm.patientNo" placeholder="" readonly/>-->
<!--                  </el-form-item>-->
<!--                </el-col>-->
              </el-row>
              <el-row :gutter="10">
                <el-col :span="8">
                  <el-form-item label="患者姓名" prop="patientName">
                    <el-input v-model="patientForm.patientName" placeholder="请输入患者名称" readonly maxlength="10"/>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="患者生日" prop="patientBirthday">
                    <el-date-picker clearable
                                    v-model="patientForm.patientBirthday"
                                    type="date"
                                    value-format="yyyy-MM-dd"
                                    placeholder="请选择患者生日"
                                    readonly >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="患者年龄" prop="patientAge">
                    <el-input v-model="patientForm.patientAge" readonly placeholder="请输入患者年龄"/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="8">
                  <el-form-item label="患者性别" prop="patientGender">
                    <el-select v-model="patientForm.patientGender" placeholder="请选择患者性别" :disabled="true" clearable>
                      <el-option
                        v-for="dict in dict.type.sys_user_sex"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                    <!--                    <el-input v-model="patientForm.patientGender" placeholder="请输入患者性别"/>-->
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="患者身高" prop="patientHeight">
                    <el-input v-model="patientForm.patientHeight" placeholder="请输入患者身高" readonly maxlength="3">
                      <i slot="append">cm</i>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="患者体重" prop="patientWeight">
                    <el-input v-model="patientForm.patientWeight" placeholder="请输入患者体重" readonly maxlength="3">
                      <i slot="append">kg</i>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="8">
                  <el-form-item label="患者民族" prop="patientFolk">
                    <el-input v-model="patientForm.patientFolk" placeholder="请输入患者民族" readonly maxlength="10"/>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="患者职业" prop="patientJob">
                    <el-input v-model="patientForm.patientJob" placeholder="请输入患者职业" readonly maxlength="10"/>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="婚姻状态" prop="patientMarriage">
                    <el-select v-model="patientForm.patientMarriage" placeholder="请选择患者状态" :disabled="true" clearable>
                      <el-option
                        v-for="dict in dict.type.marital_status"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                    <!--                    <el-input v-model="patientForm.patientMarriage" placeholder="请输入婚姻状态"/>-->
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="患者地址" prop="patientAddress">
                    <el-input v-model="patientForm.patientAddress" placeholder="请输入患者地址" readonly maxlength="30"/>
                  </el-form-item>
                </el-col>
                <el-col :span="8" :offset="4">
                  <el-form-item label="联系方式" prop="patientPhone">
                    <el-input v-model="patientForm.patientPhone" placeholder="请输入联系方式" readonly maxlength="11"/>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-row>
          </el-form>
        </el-tab-pane>

        <!--        <el-tab-pane name="2">-->
        <!--          <div slot="label" >就诊信息1</div>-->
        <!--        </el-tab-pane>-->

        <el-tab-pane name="2" label="就诊信息">
          <el-form ref="form" :rules="clinicrules" :model="form" label-width="100px" label-position="top">
            <el-row :gutter="10">
              <el-col :span="8">
                <el-form-item label="患者来源" prop="source">
                  <template>
                    <el-radio-group v-model="form.source">
                      <el-radio :label="0">门诊</el-radio>
                      <el-radio :label="1">住院</el-radio>
                    </el-radio-group>
                  </template>
                  <!--                  <el-select v-model="form.source" placeholder="请选择患者来源" clearable>-->
                  <!--                    <el-option-->
                  <!--                      v-for="dict in dict.type.patient_source"-->
                  <!--                      :key="dict.value"-->
                  <!--                      :label="dict.label"-->
                  <!--                      :value="dict.value"-->
                  <!--                    />-->
                  <!--                  </el-select>-->
                  <!--                  <el-input v-model="form.source" placeholder="请输入患者来源"/>-->
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="6">
                <el-form-item label="病种" prop="disease">
                  <el-select v-model="form.disease" placeholder="请选择患者病种" clearable>
                    <el-option
                      v-for="item in diseaseList"
                      :key="item.id"
                      :label="item.diseaseName"
                      :value="item.diseaseName"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="科室" prop="department">
                  <el-select v-model="form.department" placeholder="请选择患者科室" clearable>
                    <el-option
                      v-for="item in departmentList"
                      :key="item.id"
                      :label="item.departmentName"
                      :value="item.departmentName"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="病区" prop="ward">
                  <el-select v-model="form.ward" placeholder="请选择患者病区" clearable>
                    <el-option
                      v-for="item in wardList"
                      :key="item.id"
                      :label="item.ward"
                      :value="item.ward"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="病床" prop="bedNum">
                  <el-input v-model="form.bedNum" placeholder="请输入病床"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="24">
                <el-form-item label="诊断" prop="preDiagnose">
                  <el-input v-model="form.preDiagnose" type="textarea" placeholder="请输入内容"/>
                </el-form-item>
              </el-col>
            </el-row>
<!--            <el-row :gutter="10">-->
<!--              <el-col :span="8">-->
<!--                <el-form-item label="接诊医生/管床医生姓名" prop="manageId">-->
<!--                  &lt;!&ndash;                  <el-input v-model="form.manageId" placeholder="请输入接诊医生/管床医生编码"/>&ndash;&gt;-->
<!--                  <el-select v-model="form.manageId" placeholder="请选择接诊医生/管床医生姓名" style="width: 100%;">-->
<!--                    <el-option-->
<!--                      v-for="item in userOptions"-->
<!--                      :key="item.userId"-->
<!--                      :label="item.nickName"-->
<!--                      :value="item.userId"-->
<!--                    ></el-option>-->
<!--                  </el-select>-->
<!--                </el-form-item>-->
<!--              </el-col>-->
<!--              <el-col :span="8">-->
<!--                <el-form-item label="一线医生姓名" prop="firstDoctorId">-->
<!--                  &lt;!&ndash;                  <el-input v-model="form.firstDoctorId" placeholder="请输入一线医生编码"/>&ndash;&gt;-->
<!--                  <el-select v-model="form.firstDoctorId" placeholder="请选择一线医生姓名" style="width: 100%;">-->
<!--                    <el-option-->
<!--                      v-for="item in userOptions"-->
<!--                      :key="item.userId"-->
<!--                      :label="item.nickName"-->
<!--                      :value="item.userId"-->
<!--                    ></el-option>-->
<!--                  </el-select>-->
<!--                </el-form-item>-->
<!--              </el-col>-->
<!--              <el-col :span="8">-->
<!--                <el-form-item label="二线医生姓名" prop="secondDoctorId">-->
<!--                  &lt;!&ndash;                  <el-input v-model="form.secondDoctorId" placeholder="请输入二线医生编码"/>&ndash;&gt;-->
<!--                  <el-select v-model="form.secondDoctorId" placeholder="请选择二线医生姓名" style="width: 100%;">-->
<!--                    <el-option-->
<!--                      v-for="item in userOptions"-->
<!--                      :key="item.userId"-->
<!--                      :label="item.nickName"-->
<!--                      :value="item.userId"-->
<!--                    ></el-option>-->
<!--                  </el-select>-->
<!--                </el-form-item>-->
<!--              </el-col>-->
<!--            </el-row>-->
            <el-row :gutter="10">
              <el-col :span="24">
                <el-form-item label="病情摘要" prop="illnessSummary">
                  <el-input v-model="form.illnessSummary" type="textarea" placeholder="请输入内容"/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="既往史" prop="preHistory">
                  <el-input v-model="form.preHistory" type="textarea" placeholder="请输入既往史"/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="家族史" prop="familyHistory">
                  <el-input v-model="form.familyHistory" type="textarea" placeholder="请输入家族史"/>
                </el-form-item>
              </el-col>
            </el-row>
            <!--            <el-form-item label="患者主索引" prop="patientId">-->
            <!--              <el-input v-model="form.patientId" placeholder="请输入患者主索引"/>-->
            <!--            </el-form-item>-->
          </el-form>


        </el-tab-pane>
        <div style='float: left'>
          <ocr-asr :ocr-url="('http://10.168.1.254:5000/uploadOcr')" :asr-url="('http://10.168.1.254:5000/uploadAsr')"></ocr-asr>
        </div>
        <div style="float: right">
          <el-button type="primary" v-show="(activeName=='2')" @click="charge1">上一页</el-button>
          <el-button type="primary" v-show="(activeName=='1')" @click="charge2">下一页</el-button>
          <el-button type="primary" @click="submitForm" v-show="(activeName=='2')">提 交</el-button>
          <el-button @click="cancel" v-show="(activeName=='2')">返 回</el-button>
        </div>
      </el-tabs>

      <div slot="footer" class="dialog-footer">

      </div>
  </div>
</template>

<script>
import {listPatient, getPatient, delPatient, addPatient, updatePatient, insertPatient} from "@/api/gaoxin/patient";
import Recorder from "js-audio-recorder";
import {addClinic, updateClinic} from "@/api/gaoxin/clinic";
import {getUserAll} from "@/api/system/user";
import OcrAsr from "@/components/OcrAsr";
import {listDisease} from "@/api/system/disease";
import {listDepartment} from "@/api/system/department";
import {listWard} from "@/api/system/ward";


export default {
  name: "Patient",
  dicts: ['patient_status','sys_user_sex','marital_status'],
  components:{OcrAsr},
  data() {
    var validateName = (rule, value, callback) => {
      let patientIdentityNo = value;
      let total = 0;
      listPatient({patientIdentityNo: patientIdentityNo}).then(response => {
        total = response.total;
        if (total != 0) {
          callback(new Error('该患者已存在'));
        } else {
          callback();
        }
      })
    };
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 患者表格数据
      patientList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //医生选项
      userOptions:[],
      //病种列表
      diseaseList: [],
      //科室列表
      departmentList: [],
      //病区列表
      wardList: [],
      // 就诊查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        source: null,
        preDiagnose: null,
        manageId: null,
        firstDoctorId: null,
        secondDoctorId: null,
        illnessSummary: null,
        preHistory: null,
        familyHistory: null,
        disease: null,
        department: null,
        ward: null,
        bedNum: null,
        createTime: null,
        outTime: null,
        patientId: null,
        status: null
      },
      // 患者查询参数
      queryPatientParams: {
        pageNum: 1,
        pageSize: 10,
        patientNo: null,
        patientName: null,
        patientBirthday: null,
        patientAge: null,
        patientGender: null,
        patientIdentityNo: null,
        patientJob: null,
        patientWeight: null,
        patientHeight: null,
        patientFolk: null,
        patientAddress: null,
        patientPhone: null,
        patientMarriage: null,
        patientStatus: null,
      },
      // 表单参数
      form: {
        source: 0
      },
      // 表单参数
      patientForm: {
        patientBirthday: ''
      },

      //----弹窗----
      // pane
      activeName: "1",
      //患者下的任务是否都已审核
      isActive:true,
      //----弹窗----

      //----ocr----asr----
      vloading: false,
      ocrsen: '',
      asrsen: '',
      recorder: null,
      playTime: 0,
      timer: null,
      recorderFlag: false,
      open0: false,
      open1: false,
      //----ocr----asr----

      // 表单校验
      patientrules: {
        patientName: [
          {required: true, message: "患者名称不能为空", trigger: "blur"},
        ],
        patientIdentityNo: [
          {required: true, message: '身份证不能为空', trigger: "blur"},
          {pattern:/^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号', trigger: 'blur'},
        ],
        patientPhone: [
          {required: true, message: "患者联系方式不能为空", trigger: "blur"},
          {pattern:/^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$/, message: "请输入正确的联系方式(固话加区号)", trigger: "blur"}
        ]
      },
      clinicrules: {
        source: [
          {required: true, message: "患者来源 不能为空", trigger: "blur"},
        ]
      }
    };
  },
  created() {
    const path = this.$route.path;
    const patientId = Number(path.split('/').slice(-1));
    const query = {patientId: patientId};
    listPatient(query).then(response => {
      this.patientForm = response.rows[0];
    })
    this.getList();

    this.getDiseaseList();
    this.getDepartmentList();
    this.getWardList();
    this.getDicts("marital_status").then(res=>{
      this.marital_status=res.data;
    })
  },
  watch: {
    'patientForm.patientBirthday': {
      handler: function (newVal, oldVal) {
        console.log(newVal, oldVal);
        if(newVal != '' && newVal != null) {
          var birthdays = new Date(newVal.replace(/-/g, "/"));
          var d = new Date();
          var age =
            d.getFullYear() -
            birthdays.getFullYear() -
            (d.getMonth() < birthdays.getMonth() ||
            (d.getMonth() == birthdays.getMonth() &&
              d.getDate() < birthdays.getDate())
              ? 1
              : 0);
          this.patientForm.patientAge = age;
        }

      },
      deep: true
    }
  },
  methods: {

    checkPatient(e) {
      console.log(e);
      let value = e.target.value;
      if (value.length == 18) {
        this.$refs.checkPatient.innerText = "123";
      }
      console.log("checkPatient");
    },

    /** 查询患者列表 */
    getList() {
      this.loading = true;
      this.queryParams.patientStatus = '1'; //患者未就诊
      listPatient(this.queryParams).then(response => {
        this.patientList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getInfo() {
      getUserAll().then(response => {
        this.userOptions = response.users;
        console.log('userOptions',this.userOptions)
      });
    },
    //查询所有病种
    getDiseaseList() {
      this.loading = true;
      listDisease({pageNum: 1, pageSize: 10, diseaseName: null}).then(response => {
        this.diseaseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //查询所有科室
    getDepartmentList() {
      this.loading = true;
      listDepartment({pageNum: 1, pageSize: 10, departmentName: null}).then(response => {
        this.departmentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //查询所有病区
    getWardList() {
      this.loading = true;
      listWard({pageNum: 1, pageSize: 10, ward: null}).then(response => {
        this.wardList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.$tab.closePage();
      this.$router.go(-1);
    },
    // 表单重置
    reset() {
      this.form = {
        patientId: null,
        patientNo: null,
        patientName: null,
        patientBirthday: null,
        patientAge: null,
        patientGender: null,
        patientIdentityNo: null,
        patientJob: null,
        patientWeight: null,
        patientHeight: null,
        patientFolk: null,
        patientAddress: null,
        patientPhone: null,
        patientMarriage: null,
        patientStatus: "0",
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 详情按钮操作 */
    patdetail(row) {
      console.log('row是啥：',row)
      var temp = {
        name: 'patient_detail',
        params: {
          pat: row
        }
      }
      this.$router.push(temp)
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.patientId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加患者";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const patientId = row.patientId || this.ids
      getPatient(patientId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改患者";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.patientId = this.patientForm.patientId;
          addClinic(this.form).then(response => {
            updatePatient({patientId: this.patientForm.patientId, patientStatus: '0'});
            this.$modal.msgSuccess("操作成功");
          });

          this.$router.push("/workflow/register/index");
        }
      });
    },
    //----------------------------------------------------------
    handleClick(tab, event) {
      console.log(tab, event);
    },
    charge1() {
      this.activeName="1";
    },
    charge2() {
      this.activeName="2";
    },
    //----------------------------------------------------------
    handleClose() {
    },
    uploadFile(params) {
      // this.startLoading();
      this.vloading = true;
      // console.log(document.querySelector("#inputArea"));
      const formData = new FormData()
      formData.append('file', params.file)
      const axios = require('axios')
      axios.post("http://127.0.0.1:5000/uploadOcr", formData).then(res => {
        this.ocrsen = res.data;
        // console.log(res);
        // this.endLoading();
        this.vloading = false;
      })

    },
    // 开始录音
    startRecorder() {
      this.recorderFlag = true;
      this.recorder = new Recorder({
        sampleBits: 16, // 采样位数，支持 8 或 16，默认是16
        sampleRate: 16000, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
        numChannels: 1, // 声道，支持 1 或 2， 默认是1
      })
      // 绑定事件-打印的是当前录音数据
      this.recorder.onprogress = function (params) {
        // console.log('--------------START---------------')
        // console.log('录音时长(秒)', params.duration);
        // console.log('录音大小(字节)', params.fileSize);
        // console.log('录音音量百分比(%)', params.vol);
        // console.log('当前录音的总数据([DataView, DataView...])', params.data);
        // console.log('--------------END---------------')
      }
      this.recorder.start().then(() => {
      }, (error) => {
        // 出错了
        console.log(`${error.name} : ${error.message}`);
      });
    },
    // 继续录音
    resumeRecorder() {
      this.recorder.resume()
    },
    // 暂停录音
    pauseRecorder() {
      this.recorder.pause();
    },
    // 结束录音
    stopRecorder() {
      this.recorder.stop()
    },
    // 录音播放
    playRecorder() {
      if (this.recorderFlag === false) {
        this.$message.error({
          message: '请先录制语音！',
          center: true
        });
      }
      else {
        this.recorder.play();
        // 播放时长
        this.timer = setInterval(() => {
          try {
            this.playTime = this.recorder.getPlayTime()
          } catch (error) {
            this.timer = null
          }
        }, 100)
      }
    },
    // 暂停录音播放
    pausePlayRecorder() {
      if (this.recorderFlag === false) {
        this.$message.error({
          message: '请先录制语音！',
          center: true
        });
      }
      else {
        this.recorder.pausePlay();
      }
    },
    // 恢复录音播放
    resumePlayRecorder() {
      if (this.recorderFlag === false) {
        this.$message.error({
          message: '请先录制语音！',
          center: true
        });
      }
      else {
        this.recorder.resumePlay();
      }
    },
    // 停止录音播放
    stopPlayRecorder() {
      if (this.recorderFlag === false) {
        this.$message.error({
          message: '请先录制语音！',
          center: true
        });
      }
      else {
        this.recorder.stopPlay();
      }
    },
    // 销毁录音
    destroyRecorder() {
      if (this.recorderFlag === false) {
        this.$message.error({
          message: '请先录制语音！',
          center: true
        });
      }
      else {
        this.recorderFlag = false;
        this.recorder.destroy();
      }
    },
    // 上传语音识别
    asrRecorder() {
      if (this.recorderFlag) {
        this.vloading=true;
        const formData = new FormData()
        const blob = this.recorder.getPCMBlob();//获取 PCM 数据
        const newbolb = new Blob([blob], {type: 'audio/pcm'})
        const fileOfBlob = new File([newbolb], '录音文件' + '.pcm')
        formData.append('file', fileOfBlob)
        const axios = require('axios')
        axios.post("http://127.0.0.1:5000/uploadAsr", formData).then(res => {
          console.log(res)
          this.asrsen=res.data;
          this.vloading=false;
        })
      } else {
        this.$message.error({
          message: '请先录制语音！',
          center: true
        });
      }
    },
    // 获取麦克风权限
    getPermission() {
      Recorder.getPermission().then(() => {
        this.$Message.success('获取权限成功')
      }, (error) => {
        console.log(`${error.name} : ${error.message}`);
      });
    },
    // 打开文字识别弹窗
    handleOCR() {
      this.open0 = true;
    },
    // 打开语音识别弹窗
    handleSpeech() {
      this.open1 = true;
    },
    // 关闭识别弹窗
    cancelDialog() {
      this.open0 = false;
      this.open1 = false;
    },
    computed: {
      last () {
        return this.activeName == "1"
      },
      first() {
        return this.activeName == "2"
      }
    }
  }
};
</script>
